﻿using H.Logs;
using H.Nets;
using System;

namespace H.Logger.Logs.Listeners
{
    /// <summary>
    /// 网络日志服务器
    /// </summary>
    public class HWebLogListener : ILogListener
    {
        /// <summary>
        /// 日志客户端
        /// </summary>
        private readonly ITcpClient TcpClient;

        /// <summary>
        /// 初始化一个网络日志服务器
        /// </summary>
        /// <param name="hostName">日志服务器域名或地址</param>
        /// <param name="port">日志服务器监听端口</param>
        /// <param name="clientName">客户端名称,用于在日志服务器端进行标识</param>
        public HWebLogListener(string hostName, int port, string clientName)
        {
            TcpClient = IPlugin.GetObject<INetFactory>("H.Net")?.CreateTcpClientInstance(hostName, port) ?? throw new Exception("无法创建TcpClient实例");
            TcpClient.Identifier = clientName;
            TcpClient.Connect();
        }

        ///<inheritdoc/>
        public void Write(string str)
        {
            TcpClient.Send(HFrameType.LOG, str);
        }


        /// <summary>
        /// 关闭流
        /// </summary>
        /// <param name="disposing"></param>
        private void Dispose(bool disposing)
        {
            if (disposing) { }
            TcpClient.Disconnect();
        }

        ///<inheritdoc/>
        public void Dispose()
        {
            Dispose(true);
        }

        ~HWebLogListener()
        {
            Dispose(false);
        }

    }
}
